package com.bob.imdservice.thread;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

import com.bob.imdservice.App;
import com.bob.imdservice.AppConstants;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;




/**
  * 指令处理线程
  * @author charlie
  * create at 2017/7/10 1:53
  */

public class ServerThread implements Runnable {

	private Socket socket;

	public ServerThread(Socket socket) {
		this.socket = socket;
	}
	@Override
	public void run() {
		try {
			//获得输入流
			InputStream is=socket.getInputStream();
			System.out.println(is.toString());
			BufferedReader br=new BufferedReader(new InputStreamReader(is));
			//获得输出流
			OutputStream os=socket.getOutputStream();
			PrintWriter pw=new PrintWriter(os);
			//读取
			String s=null;
			while(!((s=br.readLine())==null)){
				System.out.println("我是服务器，用户信息为："+s);
				if (s.length() > 0){
					switch (s){
						case "install":
							//TODO : 执行安装程序
							sendMeassage(AppConstants.BCR_COMMAND,"接受到远程控制安装指令");
							sendMeassage(AppConstants.BCR_COMMAND,"执行远程安装指令 - " + s);
							sendMeassage(AppConstants.BCR_COMMAND,"程序安装中......");
							install();
							break;
						default:
							break;
					}
				}
			}
			//给客户一个响应
			String reply="complate";
			sendMeassage(AppConstants.BCR_COMMAND,"向远程控制端返回指令 complate");
			pw.write(reply);
			pw.flush();
			//5.关闭资源
			pw.close();
			os.close();
			br.close();
			is.close();
			socket.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	//TODO: 安装程序
	public void install() {
		//TODO: apk文件的本地路径
		File apkfile = new File(Environment.getExternalStorageDirectory().getPath() +
				"/Download/" + "app_fuckme.apk");
		//TODO: 会根据用户的数据类型打开android系统相应的Activity。
		Intent intent = new Intent(Intent.ACTION_VIEW);
		//TODO: 设置intent的数据类型是应用程序application
		intent.setDataAndType(Uri.parse("file://" + apkfile.toString()),
				"application/vnd.android.package-archive");
		//TODO: 为这个新apk开启一个新的activity栈
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		//TODO: 开始安装
		App.getmContext().startActivity(intent);

	}

	//TODO: 发送状态消息
	private void sendMeassage(String action,String msg){
		Intent intent = new Intent();
		intent.setAction(action);
		Bundle bundle = new Bundle();
		bundle.putSerializable("msg",msg);
		intent.putExtras(bundle);
		App.getmContext().sendBroadcast(intent);
	}

}
